cc.Class({
    //name: '11X5DirectSelectPage',
    extends: cc.Component,

    properties: {
        //标头
        labTopTitle:{
            default: null,
            type: cc.Label
        },
        //投注信息
        labShowAmount:{
           default: null,
           type: cc.Label 
        },

        //说明
        labDec:{
           default: null,
           type: cc.RichText 
        },

        labWeiDec:{
           default: [],
           type: cc.Label 
        },

        edMutipleNum:{
            default:null,
            type:cc.EditBox
        },

        edIssueNum:{
            default:null,
            type:cc.EditBox
        },

        //选择球根目录
        betContent:{
            default:[],
            type:cc.Node
        },

        //投注单根目录
        ndBetPanle:{
            default: null,
            type: cc.Node
        },

        //选择球
        tgRedBall:{
            default: null,
            type: cc.Prefab
        },

        //选择玩法按钮列表
        tgAnySelList:{
            default:[],
            type:cc.Toggle
        },

        //机选清空切换按钮
        tgSelect:{
            default:null,
            type:cc.Toggle
        },

        //红球图片
        spRedBall:{
            default: null,
            type: cc.SpriteFrame
        },

        //红球放大
        spBigRedBall:{
            default: null,
            type: cc.Sprite
        },

        tgIsStop:{
            default:null,
            type:cc.Toggle
        },

        ndAddAward:{
            default:[],
            type:cc.Node
        },

        BASEMONEY:2,//基础投资
        _rules:[],//规则
        _nums:[],//数值
        _betToggleList:[],//球指针列表
        _selRedBall:[],//选择球数字列表
        _isLoadRes:[],//是否加载
        _decContents:[],//说明列表

        _isMiss:false,//是否开启遗漏
        _lotteryID:0,//彩种id
        _totalisuse:0,//总期数
        _curMoney:0,
        _curBetNum:0,
        _curPage:1,
        _offsetX:130,//偏移x
        _offsetY:360,//偏移y
        _isStops:-1,//追号到截止
        _betManage:null
    },

    initConfig:function(){
        this._rules = [DEFINE.LOTTERYRULE115.ZHI_ONE,DEFINE.LOTTERYRULE115.ZHI_TWO,DEFINE.LOTTERYRULE115.ZHI_THREE];

        this._nums = ["01","02","03","04","05","06","07","08","09","10","11"]; 
        this._decContents = [
            "<color=#ffffff>至少选1个号码，猜对第1个开奖号即中</c><color=#fcd346>13元</color>",
            "<color=#ffffff>每位至少选1个号码，按位猜对前2个开奖号即中</c><color=#fcd346>130元</color>",
            "<color=#ffffff>每位至少选1个号码，按位猜对前3个开奖号即中</c><color=#fcd346>1170元</color>",
        ];
        this.names = ["前一直选","前二直选","前三直选"];
        this._totalisuse = 87;

        for(var i=0;i<3;i++)
        {
            var arry = [];
            this._isLoadRes.push(false);
            this._selRedBall.push(arry);
        }
        this._betManage = cc.find("Canvas").getChildByName("ChatRoomPage").getChildByName("BetManage").getComponent("BetManage");
        this._offsetX = 65;
        this._offsetY =440;
        this._isStops =-1;
    },

    initReset:function(){
         if(this._isMiss )
         {
            this._betManage.showMissArry(this._betToggleList[this._curPage-1],this._lotteryID,this._lotteryID+this._rules[this._curPage-1].toString());
         }
    },

    // use this for initialization
    onLoad: function () {
        this.node.on(cc.Node.EventType.TOUCH_END, function (event) {
                var contentRect = this.ndBetPanle.getBoundingBoxToWorld();
                var touchLocation = event.getLocation();
                contentRect.x = contentRect.x -20;
                contentRect.width = 1080;
                if(cc.rectContainsPoint(contentRect, touchLocation) == false){//关闭投注界面
                    this.onClose();
                }
        }, this);

       this.initPanel();
    },

    showAddAward:function(data){
        for(var i=0;i<data.length;i++)
        {
            var codestr = data[i].PlayCode.toString();
            var code = codestr.substring(codestr.length-2,codestr.length);
            var index = this._rules.indexOf(code); 
            if(index != -1)
            {
                var icode = parseInt(code);
                this.ndAddAward[icode-8].active = true;
            }
        }
    },

    //外部传参
    init:function(lotteryid){
        this._lotteryID = lotteryid;
        this._isStops = -1;
        this.initConfig();
    },

          //是否中奖后停止追号
    onIsStops:function(toggle, customEventData){
        if(toggle.isChecked == true)
        {
            this._isStops = 0;
        }
        else
        {
            this._isStops = -1;
        }
    },

    //初始化场景信息
    initPanel:function(){   
        this._curPage = 1;
        this.refreshPage(this._curPage);
        for(var i=0;i<this.tgAnySelList.length;i++)
        {
            var checkEventHandler = new cc.Component.EventHandler();
            checkEventHandler.target = this.node; 
            checkEventHandler.component = "11X5DirectSelectPage"
            checkEventHandler.handler = "onSelPageCallBack";
            checkEventHandler.customEventData = {
                name:this.names[i],
                pageID:i+1,
                decContent:this._decContents[i]
            };
            this.tgAnySelList[i].getComponent(cc.Toggle).checkEvents.push(checkEventHandler);
        }
        //初始选择第一个小界面
        var temp = this.tgAnySelList[0].getComponent(cc.Toggle).checkEvents[0].customEventData;
        this.onSelPageCallBack(this.tgAnySelList[0],temp);
        this._isLoadRes[0] = true;
    },

    onSelPageCallBack:function(toggle, customEventData){
        if(toggle.getComponent(cc.Toggle).isChecked)
        {
            this.labTopTitle.string = customEventData.name;
            this.labDec.string = customEventData.decContent;
            this._curPage = customEventData.pageID;
            this.refreshPage(this._curPage);
            this.clearCurSel();
            if(this._isMiss)
            {
                this._betManage.showMissArry(this._betToggleList,this._lotteryID,this._lotteryID+this._rules[this._curPage-1].toString());
            }
        }  
    },

    refreshPage:function(index){
        if(index>1)
        {
            this.labWeiDec[0].string = "万位";
        }
        else
        {
            this.labWeiDec[0].string = "选号";
        }
        for(var i = 0;i<3;i++)
        {
            if(index>=i+1)
            {
                if(this._isLoadRes[i])
                {
                    this.betContent[i].active = true;
                    this.labWeiDec[i].node.active = true;
                }
                else
                {
                    var arry = [];
                    for(var j = 0;j<this._nums.length;j++)
                    {      
                        var ball = cc.instantiate(this.tgRedBall);
                        ball.getComponent('Bet_toggle_ball').init({
                            num: this._nums[j],
                            miss: ""
                        });
                        var checkEventHandler = new cc.Component.EventHandler();
                        checkEventHandler.target = this.node; 
                        checkEventHandler.component = "11X5DirectSelectPage"
                        checkEventHandler.handler = "onClickCallback";
                        checkEventHandler.customEventData = {num:j+1,type:i};
                        ball.getComponent(cc.Toggle).checkEvents.push(checkEventHandler);
                        this.betContent[i].addChild(ball);
                        arry.push(ball);
   
                        //事件监听
                        //当手指在目标节点区域内离开屏幕时。
                        ball.on(cc.Node.EventType.TOUCH_END, function (event) {
                            this.spBigRedBall.node.y = 10000;
                             
                        },this);

                        //当手指在目标节点区域外离开屏幕时。
                        ball.on(cc.Node.EventType.TOUCH_CANCEL, function (event) {
                            this.spBigRedBall.node.y = 10000;
                               
                        },this);

                        //当手指触摸到屏幕时。
                        ball.on(cc.Node.EventType.TOUCH_START, function (event) {
                            if(ball.active != true)
                            {
                                return;
                            }
                            
                            var curTg = event.getCurrentTarget();
                            var type = curTg.getComponent(cc.Toggle).checkEvents[0].customEventData.type;
                           
                            if(type > this._curPage-1 )
                            {
                                return;
                            }
                            this.spBigRedBall.node.getChildByName("labnum").getComponent(cc.Label).string = curTg.getComponent('Bet_toggle_ball').getNum();
                            this.spBigRedBall.node.x = curTg.x+this._offsetX ;
                            this.spBigRedBall.node.y = curTg.y+this._offsetY - ((type)*330);
                           
                        },this);

                        //当鼠标在目标节点在目标节点区域中移动时，不论是否按下。
                        ball.on(cc.Node.EventType.MOUSE_MOVE, function (event) {
                            var curTg = event.getCurrentTarget();
                            var contentRect = curTg.getBoundingBoxToWorld();
                            var touchLocation = event.getLocation();
                            if(cc.rectContainsPoint(contentRect, touchLocation) == false){
                                this.spBigRedBall.node.y = 10000;
                              
                            }  
                           
                        },this);

                        //当手指在屏幕上目标节点区域内移动时。
                        ball.on(cc.Node.EventType.TOUCH_MOVE, function (event) {
                        
                            var curTg = event.getCurrentTarget();
                            var contentRect = curTg.getBoundingBoxToWorld();
                            var touchLocation = event.getLocation();
                            if(cc.rectContainsPoint(contentRect, touchLocation) == false){
                               
                                this.spBigRedBall.node.y = 10000;
                            }  
                        },this);
                    }
                    this._betToggleList.push(arry);
                    this._isLoadRes[i] = true;
                    this.betContent[i].active = true;
                    this.labWeiDec[i].node.active = true;
                }
            }
            else
            {
                this.labWeiDec[i].node.active = false;
                this.betContent[i].active = false;
            }
        }
    },

    onClickCallback:function(toggle, customEventData){
       
        var num = customEventData.num;
        var type = customEventData.type;
        if(toggle.getComponent(cc.Toggle).isChecked)
        {
            for(var i=0;i<this._betToggleList.length;i++)
            {
                if(i == type)
                    continue;

                if(this._betToggleList[i][num-1].getComponent(cc.Toggle).isChecked) 
                {
                    this._betToggleList[i][num-1].getComponent(cc.Toggle).isChecked = false;
                    Utils.removeByValue(this._selRedBall[i],num);
                    break;
                }
            }
            this._selRedBall[type].push(num);
        }
        else
        {
             Utils.removeByValue(this._selRedBall[type],num);
        }
        this.updateTgSelect();
        this.checkBet();
    },

    updateTgSelect:function(){
        for(var i=0;i<this._selRedBall.length;i++)
        {
            if(this._selRedBall[i].length > 0)
            {
                this.tgSelect.getComponent(cc.Toggle).isChecked = true;
                return;
            }
        }
        this.tgSelect.getComponent(cc.Toggle).isChecked = false;
    },

      //设置金额
    setMoney:function(mon){
        this._curMoney = mon;
    },

    //得到金额
    getMoney:function(){
        return this._curMoney;
    },

    //设置注数
    setBetNum:function(num){
        this._curBetNum = num;
    },

    //得到注数
    getBetNum:function(){
        return this._curBetNum;
    },

    //设置期数
    setIssueNum:function(num){
        if(this._totalisuse >= parseInt(num))
        {
            this.edIssueNum.string = num;
        }
        else
        {
            ComponentsUtils.showTips("最大只能选择87期");
            this.edIssueNum.string = this._totalisuse.toString();
        }
        this.checkBet();
    },

    //得到期数
    getIssueNum:function(){
        var num = parseInt(this.edIssueNum.string);
        if(isNaN(num)){ 
            return 1;
        }else{
            return num;
        }        
    },

       //手动期数
    onEditBoxIssueChanged:function(editbox) {
        if(!Utils.isInt(editbox.string))
        {
            ComponentsUtils.showTips("输入格式错误！");
            editbox.string = "1";
        }
        if(editbox.string == null || editbox.string == "")
        {
            editbox.string = "1";
            ComponentsUtils.showTips("倍数不能为空！");
        }

        var amount = parseInt(editbox.string);
          if(isNaN(amount) || amount<=0 ){
            editbox.string = "1";
        }
  
       this.setIssueNum(editbox.string);
    },

    //设置倍数
    setMutipleAmount:function(mutiple){
         this.edMutipleNum.string = mutiple;
         this.checkBet();
    },

    //获取当前倍数
    getMutipleAmount:function(){
        var amount = parseInt(this.edMutipleNum.string);
        if(isNaN(amount)){ 
            return 1;
        }else{
            return amount;
        }        
    },

    //手动倍数
    onEditBoxMutipleChanged:function(editbox) {
        if(!Utils.isInt(editbox.string))
        {
            ComponentsUtils.showTips("输入格式错误！");
            editbox.string = "1";
        }
        if(editbox.string == null || editbox.string == "")
        {
            editbox.string = "1";
            ComponentsUtils.showTips("倍数不能为空！");
        }

        var amount = parseInt(editbox.string);
        if(isNaN(amount) || amount > 999 || amount<=0 ){
            editbox.string = "1";
        }
  
        this.checkBet();
    },

    //显示投注信息
    setShowAmount:function(mut,bet){
        var issue = this.getIssueNum();
        var money = mut*bet*this.BASEMONEY*issue;
        this.setMoney(money);
        this.setBetNum(bet);
        this.labShowAmount.string = "共"+bet+"注"+ mut +"倍"+ issue + "期"+ money+"元";
    },

    //重置界面
    clearAllBetRecord:function(){
        this.clearCurSel();
    },

    //计算投注规则
    checkBet: function(){
        var bet = 1;
        for(var i=0;i<this._curPage;i++)
        {
            if(this._selRedBall[i].length == 0)
            {
                bet = 0;
                break;
            }
            else
            {
                bet = this._selRedBall[i].length*bet;
            }
        }
        var muiple = this.getMutipleAmount();
        this.setShowAmount(muiple,bet);
    },

    //投注信息组合
    dataToJson:function(){
        var obj = new Object(); 
        obj.PlayCode = parseInt(this._lotteryID + this._rules[this._curPage-1].toString()); 
        var num = "";
        var nums = ""
        for(var i=0;i<this._curPage;i++)
        {
            Utils.sortNum(this._selRedBall[i]);
            num = "";
            for(var j=0;j<this._selRedBall[i].length;j++)
            {
                if(num != "")
                {
                    num+=",";
                }
                var oneNum = this._selRedBall[i][j]>9 ? this._selRedBall[i][j].toString():"0"+this._selRedBall[i][j].toString(); 
                num += oneNum;
            }
            if(nums == "")
            {
                nums = num;
            }
            else
            {
                nums = nums + "|" + num;
            }
        }

        var arry = [];
        var numArrays = {
            "Multiple":this.getMutipleAmount(),
            "Bet":this.getBetNum(),
            "isNorm":1,
            "Number":nums
        };
        arry.push(numArrays);
        obj.Data = arry;
        var json = JSON.stringify(obj);
        cc.log("提交订单：" + json);
        return json;
    },

    //追号组合支付
    chasePay:function(){
        var recv = function(ret){
            ComponentsUtils.unblock(); 
            if(ret.Code === 0)
            {
                var len = ret.Data.length;
                if(len != this.getIssueNum())
                {
                    this.setIssueNum(len);
                    this.setShowAmount();
                }
                var obj = new Object(); 
                obj.Stops = this._isStops;
                obj.IsuseCount = len;
                obj.BeginTime = ret.Data[0].BeginTime;
                obj.EndTime = ret.Data[len-1].EndTime;
                var arry = [];
                for(var i=0;i<ret.Data.length;i++)
                {
                    var numArrays = {
                        "IsuseID":ret.Data[i].IsuseCode,
                        "Amount": LotteryUtils.moneytoClient(this.getMoney()/this.getIssueNum()),//每期金额
                        "Multiple":this.getMutipleAmount(),//每期总倍数
                    };
                    arry.push(numArrays);
                }
                obj.Data = arry;
                var json = JSON.stringify(obj);

                var data = {
                    lotteryId:this._lotteryID,//彩种id
                    dataBase:this.dataToJson(),//投注信息
                    otherBase:json,//追号
                    money:this.getMoney(), 
                    buyType: this.getIssueNum() >1?1:0,//追号
                }
                window.Notification.emit("BET_ONPAY",data);
            }
            else
            {
                ComponentsUtils.showTips(ret.Msg);
            }
        }.bind(this);
        var data = {
            Token:User.getLoginToken(),
            LotteryCode:this._lotteryID,
            Top:this.getIssueNum(),
        }
        CL.HTTP.sendRequest(DEFINE.HTTP_MESSAGE.GETADDTOISUSE, data, recv.bind(this),"POST");   
        ComponentsUtils.block();    
    },

    //付款
    onPayBtn:function(){
        if(this.getMoney() <= 0)
            return;
        
        if(this.getIssueNum()<=1)
        {
            var data = {
                lotteryId:this._lotteryID,//彩种id
                dataBase:this.dataToJson(),//投注信息
                otherBase:"",//追加
                money:this.getMoney(),
                buyType: 0,//追号
            }
            window.Notification.emit("BET_ONPAY",data);
        }
        else
        {
            this.chasePay();
        }
    },

    //清空当前选择
    clearCurSel:function(){
        for(var i=0;i<this._selRedBall.length;i++)
        {
            this._selRedBall[i].length = 0;
        }

        for(var i=0;i<this._betToggleList.length;i++)
        {
            for(var j=0;j<this._betToggleList[i].length;j++)
            {
                this._betToggleList[i][j].getComponent(cc.Toggle).isChecked = false;
            }
        }

        this._isStops = -1;
        this.tgIsStop.getComponent(cc.Toggle).isChecked = false;
        this.spBigRedBall.node.y = 10000;
        this.tgSelect.getComponent(cc.Toggle).isChecked = false;
        this.setIssueNum(1);
        this.setMutipleAmount(1);
        this.checkBet();
    },

    //机选
    randomSelectCallBack:function(){
        this.clearCurSel();
        var tempnum = [];
        for(var i=0;i<this._curPage;i++)
        {
            var randomArray = Utils.getRandomArrayWithArray(this._betToggleList[i], 1);
            var temp = randomArray[0].getComponent(cc.Toggle).checkEvents[0].customEventData;
            
            while(1)
            {
                if(Utils.findValueByArry(tempnum,temp.num))
                {
                    randomArray = Utils.getRandomArrayWithArray(this._betToggleList[i], 1);
                    temp = randomArray[0].getComponent(cc.Toggle).checkEvents[0].customEventData;
                }
                else
                {
                    break;
                }
            }
         
            tempnum.push(temp.num);
            randomArray[0].getComponent(cc.Toggle).isChecked = true; 
            this.onClickCallback(randomArray[0],temp);
        }
    },

    //选择清空切换
    onSelectCallBack:function(toggle){
        if(this.isNorm == 0)
        {
            toggle.getComponent(cc.Toggle).isChecked = true;
            this.clearCurSel();
        }
        else
        {
            if(toggle.getComponent(cc.Toggle).isChecked)
            {
                this.randomSelectCallBack();
            }
            else
            {
                this.clearCurSel();
            }
        }
    },

    onClose:function(){
        window.Notification.emit("BET_ONCLOSE","");
    },

    onNextPage:function(){
        window.Notification.emit("BET_NEXTPAGE",1);
    },

    onLastPage:function(){
        window.Notification.emit("BET_NEXTPAGE",-1);
    },

    onMiss:function(toggle){
        if(toggle.getComponent(cc.Toggle).isChecked)
        {
            this._isMiss = true;
            this._betManage.showMissArry(this._betToggleList,this._lotteryID,this._lotteryID+this._rules[this._curPage-1].toString());
        }    
        else
        {
            this._isMiss = false;
            this._betManage.setMissArry(false,this._betToggleList,"");
        }
    }

});
